package cn.itcast.controller.system;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController {

    @Autowired
    public DeptService deptService;

    @RequestMapping(value = "/list", name = "查询所有部门数据")
    public String fandAll(@RequestParam(defaultValue = "1", name = "page") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
        PageInfo<Dept> page = deptService.findPage(getCompanyId(), pageNum, pageSize);
        request.setAttribute("page", page);
        return "system/dept/dept-list";
    }

    @RequestMapping(value = "/toAdd", name = "进入到添加部门的页面")
    public String toAdd() {
        List<Dept> list = deptService.findAll(getCompanyId());
        request.setAttribute("deptList", list);
        return "system/dept/dept-add";
    }

    @RequestMapping(value = "/edit", name = "保存部门数据")
    public String edit(Dept dept) {
        if (dept.getParent().getId().equals("")) {
            dept.getParent().setId(null);
        }

        if (StringUtils.isEmpty(dept.getId())) {
            dept.setId(UUID.randomUUID().toString());
            dept.setCompanyId(getCompanyId());
            dept.setCompanyName(getCompanyName());
            deptService.save(dept);
        } else {
            deptService.update(dept);
        }
        return "redirect:/system/dept/list.do";
    }

    @RequestMapping(value = "/toUpdate", name = "进入修改部门页面")
    public String toUpdate(String id) {
        Dept byId = deptService.findById(id);
        request.setAttribute("dept", byId);
        List<Dept> list = deptService.findAll(getCompanyId());
        request.setAttribute("deptList", list);
        return "system/dept/dept-add";
    }

    @RequestMapping(value = "/delete", name = "删除部门方法")
    public String delete(String id) {
        deptService.deleteById(id);
        return "redirect:/system/dept/list.do";
    }
}
